﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using GameView.Comment;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Services.Dtos.Project;
using GameView.Services.Dtos.RechargesDto;
using System.Collections.ObjectModel;
using System.Windows.Controls;

namespace GameView.ViewModels
{
    public partial class RechargeToMViewModel : ObservableObject
    {
        private readonly ProjectService _proService;
        private readonly UserService _userService;

        private readonly RechargeToMService _service;

        public RechargeToMViewModel(RechargeToMService service, UserService userService, ProjectService proService, IMessenger messenger)
        {
            _proService = proService;
            _userService = userService;
            _service = service;
            IsMerchant = StaticValues.LoginInfo.PersonInfo.RoleId != 3;
            LoadData().ConfigureAwait(false);
        }

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private int _pageIndex = 1;

        [ObservableProperty]
        private int _pageSize = 50;

        [ObservableProperty]
        private int _totalCount = 0;

        [ObservableProperty]
        private int _totalPages = 1;

        [ObservableProperty]
        private bool _hasPrevPages = false;

        [ObservableProperty]
        private bool _hasNextPages = true;

        [ObservableProperty]
        private ObservableCollection<RechargeToMerchantEntity> _rechargeRecords;

        [ObservableProperty]
        private int _pageNumber = 1;

        [ObservableProperty]
        private long _sumAdd = 0;

        [ObservableProperty]
        private long _sumSub = 0;

        [ObservableProperty]
        private RechargeQueryDto _queryDto = new();

        [ObservableProperty]
        private ObservableCollection<string> _merchantOptions = [];

        [ObservableProperty]
        private string _selectedMerchant;

        [ObservableProperty]
        private bool _isMerchant = true;

        [ObservableProperty]
        private ObservableCollection<string> _projectOptions = [];

        [ObservableProperty]
        private string _selectedProject;

        [RelayCommand]
        private async Task FirstPage()
        {
            PageIndex = 1;
            PageNumber = 1;
            await LoadData();
        }

        [RelayCommand]
        private async Task PreviousPageAsync()
        {
            PageIndex--;
            PageNumber--;
            await LoadData();
        }

        [RelayCommand]
        private async Task NextPageAsync()
        {
            PageIndex++;
            PageNumber++;
            await LoadData();
        }

        [RelayCommand]
        private void LastPage() => PageIndex = TotalPages;

        [RelayCommand]
        private async Task ChangePageSize(object size)
        {
            ComboBoxItem cb = (ComboBoxItem)size;
            //PageSize = 20;
            if (cb.Content is string sizeStr && int.TryParse(sizeStr.Replace("条/页", ""), out var newSize))
            {
                PageSize = newSize;
                PageIndex = 1; // 重置到第一页
                await LoadData();
            }
        }

        [RelayCommand]
        private async Task SearchAsync()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                PageIndex = 1;
                await LoadFromApi();
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

          partial void OnSelectedProjectChanged(string value)
        {
            MerchantOptions.Clear();
            if (!string.IsNullOrEmpty(value))
            {
                _ = SetUser(value);
            }
        }

        private async Task SetUser(string pName)
        {
            var ps = await _userService.GetMersByprojectNameAsync(pName);
            if (ps == null || ps.Data.IsNullOrEmpty())
                return;
            foreach (var game in ps.Data)
            {
                MerchantOptions.Add(game.Account);
            }
        }

        [RelayCommand]
        private async Task LoadData()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                await LoadFromApi();
                List<ProjectWithGamesInfo> pgs = [];
                if (StaticValues.LoginInfo.PersonInfo.RoleId != 1)
                {
                    var res = await _proService.GetByPersonIdAsync();
                    pgs = res.Data;
                }
                else
                {
                    var res = await _proService.GetAllAsync();
                    pgs = res.Data;
                }

                ProjectOptions.Clear();
                MerchantOptions.Clear();
                pgs ??= [];
                foreach (var data in pgs)
                {
                    ProjectOptions.Add(data.Name);
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

        private async Task LoadFromApi()
        {
            QueryDto.PageIndex = PageIndex;
            QueryDto.PageSize = PageSize;
            QueryDto.ProjectName = SelectedProject;

            QueryDto.Merchant = SelectedMerchant;

            var st = await _service.GetBySTAsync(QueryDto);
            if (st != null && st.Data != null && st.Data.Count >= 2)
            {
                SumAdd = st.Data[0];
                SumSub = st.Data[1];
            }
            var res = await _service.GetPageAsync(QueryDto);
            if (res.StatusCode != 200)
            {
                GlobalMessage.Instance.ShowError(JSON.Serialize(res.Errors));
                return;
            }
            PageSize = res.Data.PageSize;
            TotalPages = res.Data.TotalPages;
            TotalCount = res.Data.TotalCount;
            HasNextPages = res.Data.HasNextPages;
            HasPrevPages = res.Data.HasPrevPages;
            PageIndex = res.Data.PageIndex;
            if (res.Data.Items == null)
                return;
            RechargeRecords = new(res.Data.Items);
        }
    }
}